<template>
  <div class="box">
    <div class="box1">
      <div class="boxTree">
        <span>组织机构</span>
        <el-tree
          style="max-width: 600px; margin-top: 10px"
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
        />
      </div>
    </div>
    <div class="box2">
      <div class="boxFilter">
        <el-form :inline="true" :model="formData">
          <el-form-item label="机构名称">
            <el-input
              placeholder="请输入组织机构名称"
              v-model="formData.deptName"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">
              <span></span>搜索
            </el-button>
            <el-button type="default" @click="resetSearch"> 重置 </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="boxTable">
        <!-- 按钮组 -->
        <el-row>
          <el-col :span="12">
            <el-button type="primary" @click="addFlag = true">
              <span></span>新增机构
            </el-button>
            <!--            <el-button >-->
            <!--              <span ></span>批量删除-->
            <!--            </el-button>-->
            <el-button> <span></span>导入 </el-button>
            <el-button> <span></span>导出 </el-button>
          </el-col>
        </el-row>
        <!-- 按钮组 -->
        <!-- 表格 -->
        <el-table
          :data="tableData"
          :border="true"
          @selection-change="onSelectionChange"
        >
          <el-table-column
            type="selection"
            align="center"
            fixed="left"
          ></el-table-column>
          <el-table-column label="序号" prop="index" align="center" width="120">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="组织名称"
            prop="deptName"
            align="center"
          ></el-table-column>
          <!--          <el-table-column label="组织层级" prop="leader" align="center" width="160"></el-table-column>-->
          <el-table-column
            label="负责人"
            prop="leader"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120"
            fixed="right"
          >
            <template #default="scoped">
              <el-button
                type="primary"
                link
                size="small"
                @click="onUpdate(scoped.row)"
              >
                <span class="iconfont icon-bianji"></span>修改
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click="deleteFn(scoped.row.id)"
              >
                <span class="iconfont icon-shanchu"></span>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--        <el-pagination-->
        <!--          background-->
        <!--          layout="total, jumper, prev, pager, next, sizes"-->
        <!--          :total="tableData.length"-->
        <!--          :page-sizes="[2,5, 10, 20, 40, 100]"-->
        <!--          @change='change'-->
        <!--          style='margin-top: 10px;float: right'-->
        <!--        >-->
        <!--        </el-pagination>-->
        <!-- 表格 -->
      </div>
    </div>
  </div>
  <el-dialog v-model="addFlag" title="新增组织机构" width="600">
    <el-form :rules="formRules" label-width="auto">
      <el-form-item label="组织名称" prop="deptName">
        <el-input v-model="deptName" placeholder="组织名称"></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="leader" placeholder="负责人"></el-input>
      </el-form-item>
      <el-form-item label="上级组织" prop="parentId">
        <el-tree-select
          v-model="parentId"
          :data="[{ deptName: '一级机构', id: 0, children: treeData }]"
          :props="defaultProps"
          check-strictly="true"
          :render-after-expand="true"
        />
      </el-form-item>
      <el-form-item label="顺序" prop="orderNum">
        <el-input v-model="orderNum" placeholder="顺序"></el-input>
      </el-form-item>
      <el-button type="primary" @click="addFn">确认</el-button>
      <el-button type="primary" @click="addFlag = false">取消</el-button>
    </el-form>
  </el-dialog>
  <el-dialog v-model="updateFlag" title="修改组织机构" width="600">
    <el-form :rules="formRules" label-width="auto">
      <el-form-item label="组织名称" prop="deptName">
        <el-input v-model="deptName" placeholder="组织名称"></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="leader" placeholder="负责人"></el-input>
      </el-form-item>
      <el-form-item label="上级组织" prop="parentId">
        <el-tree-select
          v-model="parentId"
          :data="[{ deptName: '一级机构', id: 0, children: treeData }]"
          :props="defaultProps"
          check-strictly="true"
          :render-after-expand="true"
        />
      </el-form-item>
      <el-form-item label="顺序" prop="orderNum">
        <el-input v-model="orderNum" placeholder="顺序"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="updateFn">确认</el-button>
    <el-button type="primary" @click="updateFlag = false">取消</el-button>
  </el-dialog>
</template>
<script setup>
import {
  getzzList,
  addZz,
  updateZz,
  deleteZz,
  getSearchList
} from '../../../api/zzjg/zzgl'
import { ref, onMounted, watch, reactive, watchEffect } from 'vue'

onMounted(() => {
  getData()
})
const treeData = ref({})
const tableData = ref([])
const tableDataSearch = ref([])
const defaultProps = {
  children: 'children',
  label: 'deptName',
  value: 'id'
}
const getData = () => {
  getzzList().then((res) => {
    treeData.value = res.data
    tableData.value = tableFor(treeData.value)
    tableDataSearch.value = tableFor(treeData.value)
  })
}
const handleNodeClick = (data) => {
  console.log(data)
  console.log(typeof data)
  tableData.value = tableFor(data)
  console.log(tableData.value)
}
const tableFor = (data) => {
  let newData = []
  // 定义递归函数，用于处理数据的嵌套
  const processItem = (item) => {
    newData.push(item) // 将当前 item 添加到 newData 数组中
    if (item.children && item.children.length > 0) {
      // 如果当前 item 有 children，并且 children 数组不为空，则递归处理 children
      item.children.forEach((child) => processItem(child))
    }
  }
  console.log(Array.isArray(data))
  let dataArray = []
  if (!Array.isArray(data)) {
    dataArray = [data]
  } else {
    dataArray = data
  }
  // 处理传入的初始数据
  if (dataArray && dataArray.length > 0) {
    dataArray.forEach((item) => processItem(item))
  }
  return newData
}
//---------------------新增
const addFlag = ref(false)
const deptName = ref('')
const leader = ref('')
const parentId = ref()
const orderNum = ref()
const addFn = () => {
  let data = {
    deptName: deptName.value,
    leader: leader.value,
    parentId: parentId.value,
    orderNum: orderNum.value
  }
  console.log(data)
  console.log(formRules)
  addZz(data).then((res) => {
    console.log(res)
    if (res.code == '200') {
      ElMessage.success('新增成功')
      getData()
      addFlag.value = false
    } else {
      ElMessage.error('新增失败')
    }
  })
}
// watch(addFlag,(val)=>{
//   if(!val){
//     clear()
//   }
// })
const updateFlag = ref(false)
//--------------------重置
const clear = () => {
  deptName.value = ''
  leader.value = ''
  parentId.value = ''
  orderNum.value = ''
}
watchEffect(() => {
  if (!addFlag.value && !updateFlag.value) {
    clear()
  }
})
//--------------------修改

const updateId = ref()
const onUpdate = (obj) => {
  updateFlag.value = true
  deptName.value = obj.deptName
  leader.value = obj.leader
  parentId.value = obj.parentId
  orderNum.value = obj.orderNum
  updateId.value = obj.id
}
const updateFn = () => {
  let data = {
    deptName: deptName.value,
    leader: leader.value,
    parentId: parentId.value,
    orderNum: orderNum.value,
    id: updateId.value
  }
  console.log(data)
  updateZz(data).then((res) => {
    console.log(res)
    if (res.code == '200') {
      ElMessage.success('修改成功')
      updateFlag.value = false
      getData()
    } else {
      ElMessage.error('修改失败')
    }
  })
}
//--------------------删除
const deleteFn = (id) => {
  let data = {
    id: id
  }
  deleteZz(data).then((res) => {
    console.log(res)
    if (res.code == '200') {
      ElMessage.success('删除成功')
      getData()
    } else {
      ElMessage.error('删除失败')
    }
  })
}
//-----------------------搜索
const formData = ref({})
const search = () => {
  console.log(formData.value.deptName)
  // let newSearchArr = []
  // tableDataSearch.value.forEach(item=>{
  //   if(item.deptName==formData.value.deptName){
  //     newSearchArr.push(item)
  //   }
  // })
  // tableData.value = newSearchArr
  let data = {
    deptName: formData.value.deptName
  }
  getSearchList(data).then((res) => {
    console.log(res)
    tableData.value = res.data
  })
  // console.log(tableData.value)
}
const resetSearch = () => {}
//----------------------验证规则
const formRules = reactive({
  deptName: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 10, message: '请输入2~10个字符', trigger: 'blur' }
  ],
  leader: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 2, max: 6, message: '请输入2~6个字符', trigger: 'blur' }
  ],
  parentId: [{ required: true, message: '请选择上级组织', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请选择组织顺序', trigger: 'blur' }]
  // password: [
  //   { validator: checkPassword, message: '请输入6~12个字符', trigger: 'blur' }
  //   // { required: true, message: '请输入密码', trigger: 'blur' },
  //   // { min: 6, max: 12, message: '请输入6~12个字符', trigger: 'blur' }
  // ],
  // mobile: [
  //   { required: true, message: '请输入手机号', trigger: 'blur' },
  //   { validator: checkMobile, trigger: 'blur' }
  // ]
})
</script>
<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;

  .box1 {
    width: 22%;
    height: 100%;

    .boxTree {
      width: 85%;
      height: 100%;
      padding: 16px;
      background-color: #fff;
    }
  }

  .box2 {
    width: 78%;
    height: 100%;

    .boxFilter {
      width: 100%;
      height: 10%;
      padding: 16px;
      background-color: #fff;
      padding-bottom: 0;
      margin-bottom: 10px;
      box-sizing: border-box;
    }

    .boxTable {
      padding: 16px;
      overflow: hidden;
      background-color: #fff;
      height: 88.7%;

      display: flex;
      flex-direction: column;
    }
  }
}
.input-context {
  width: 220px;
  margin-bottom: 10px;
  margin-top: 10px;
  margin-right: 5px;
}
.update-div {
  width: 100%;
  padding: 10px;
  display: flex;
}
.el-form-item__label {
  width: 30% !important;
}
</style>
